<?php
/**
 * Class Common
 * Desc  公共控制器
 * Create on 2023/8/17 11:26
 * Create by wangyafang
 */

namespace app\api\controller\wdsxh;


use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\App;
use think\Config;
use think\Hook;
use think\Lang;

class Common extends Api
{
    protected $noNeedLogin = ['upload'];
    protected $noNeedRight = '*';
    //上传方法
    public function upload()
    {
        // 自定义鉴权判断
        // 强烈建议这里判断$file = $this->request->file('file');的后缀和mimetype

        // 载入语言包，避免出现英文错误提示
        Lang::load(APP_PATH . 'api/lang/zh-cn.php');

        // 获取上传配置
        $uploadConfig = Config::get("upload");

        // 兼容云存储上传
        if ($uploadConfig['storage'] != 'local') {
            // 这里可以修改允许上传文件的后缀或修改存储的文件路径，例如只允许上传图片
            set_addon_config($uploadConfig['storage'], ['savekey' => '/uploads/{year}{mon}{day}/{filemd5}{.suffix}', 'mimetype' => 'jpg,png,bmp,jpeg,gif'], false);

            // 添加允许上传的行为
            Hook::add('upload_config_checklogin', function () {
                return true;
            });

            request()->param('isApi', true);
            App::invokeMethod(["\\addons\\{$uploadConfig["storage"]}\\controller\\Index", "upload"], ['isApi' => true]);
        } else {
            // 这里可以修改允许上传文件的后缀或修改存储的文件路径，例如只允许上传图片
            //Config::set('upload', array_merge($uploadConfig, ['savekey' => '/uploads/{year}{mon}{day}/{filemd5}{.suffix}', 'mimetype' => 'jpg,png,bmp,jpeg,gif']));

            $attachment = null;
            // 默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }
            $this->success('上传成功', '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
    }
}



 